<?php

App::uses("String", "Utility");    
App::uses('AttachUtil', 'Lib');

class UploadController extends AppController {
    // var $helpers = array ('Html','Form');
    var $name = 'Upload'; // riferimento alla cartella delle view

    // questa riga permette di utilizzare il componente Permission
    var $components = array('Permission','Thumb');
        
    public function beforeFilter(){
		parent::beforeFilter();
        // don't require logging in for login and logout actions
        $this->Auth->allow('ajaxUpload','delete','save');
    	$this->loadModel('Attach');
    }

	public function beforeRender(){

	}
    
    public function index() {
		// $this->layout="ajax";
		// $this->autorender = false;
    	// App::uses("UploadHandler", "Lib/jqueryupload");
		// $upload_handler = new UploadHandler();
		// die;
		
		$attachTipo = "FOTO";
		$this->set("attachTipo",$attachTipo);
		$attaches = $this->Attach->find("all",array("conditions" => array("Attach.attach_tipo" => $attachTipo)));
		$this->set("attaches",$attaches);
		
    }

	public function save() {
    	try {
			//print_r($this->request->data["attachTipo"]);die;
    		if (AttachUtil::upload($this->Attach, "attach", $this->request->data["attachTipo"])) {
				if ($this->Attach->attachTipo->field("thumb")) {
					try {
						$this->Thumb->generateThumb($this->Attach->getAbsolutePath(), $this->Attach->filename, $this->Attach->field("tipo"));
			    	} catch (exception $e) {
						$this->Attach->delete();
						throw $e;
			    	}
				}
    		} else {
    			throw new Exception(__("Upload del file non riuscito."));
    		}
    	} catch (exception $e) {
	    	CakeLog::error($e->getMessage());
			$this->Session->setFlash($e->getMessage(),"default",null,"error");
    	}
		$this->redirect("/upload/index");
    }

	public function ajaxUpload_old($inputName) {
		// per tutte le chiamate imposto l'ajax layout
		$this->layout="ajax";
		$this->autorender = false;
    	App::uses("UploadHandler", "Lib/jqueryupload");
		$upload_handler = new UploadHandler();
		$post = $upload_handler->post(false);
		// CakeLog::debug("eccomi ".json_encode($post));
		echo json_encode($post);
		die;		
		if($this->request->is('ajax')) {
			if ($this->upload($inputName))
				echo json_encode(array('path'=>$this->webroot.$this->Attach->getThumbFile(),'id'=>$this->Attach->id,'webroot'=>$this->webroot));
			die();
		} else {
			$this->set("name",__("Pagina inesistente."));
			$this->set("url",$this->request->url);
			$this->render("/Errors/error400");
		}
	}

     function exit_status($str,$error=''){
        echo json_encode(array('status'=>$str,'err'=>$error));
        exit;
     }

	public function ajaxUpload($inputName=null) {
        $this->layout="ajax";
        $this->autorender = false;
        $upload_dir = TMP.'uploads';
		if  (!file_exists($upload_dir)) {
			mkdir($upload_dir, 0777);
		}				
        $allowed_ext = array('jpg','jpeg','png','gif');
        if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
            $this->exit_status(__('Errore nella richiesta http.'));
        }
        if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
            $pic = $_FILES['pic'];
            if(!in_array(strtolower(pathinfo($pic['name'], PATHINFO_EXTENSION)),$allowed_ext)){
                $this->exit_status(__('Esclusivamente i seguenti %d file possono essere caricati.', implode(',',$allowed_ext)),'FileNotAllowed');
            }   
            // Move the uploaded file from the temporary
            // directory to the uploads folder:
            if(move_uploaded_file($pic['tmp_name'], $upload_dir."/".$pic['name'])){
                $this->exit_status(__('Il file è stato caricato correttamente.'));
            }
        }
        $this->exit_status(__('Errore imprevisto in fase di caricamento!'));
        // Helper functions
       exit;
	}
	
	public function delete($id) {
		$this->layout="ajax";
		$this->autorender = false;
		if($this->request->is('ajax')) {
			$this->Attach->read(null,$id);
			$this->Attach->delete();
		} else {
			$this->set("name",__("Pagina inesistente."));
			$this->set("url",$this->request->url);
			$this->render("/Errors/error400");
		}
	}

}
?>